package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String fileServerUrl;

    // http://api.gmall.com/admin/product/fileUpload
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception {
        /**
         * client:发起请求
         * tracker:定向到可存储位置
         * storage:文件上传，自动生成文件ID，并保存到磁盘中，并返回文件URL
         * 必须还需要借助 nginx 做代理才能获取文件的全路径
         * 1.加载配置文件track.conf
         * 2.初始化当前文件
         * 3.创建trackerClient
         * 4.创建trackerServer
         * 5.创建StorageClient
         * 6.文件上传
         */
        String path = "";
        // 加载配置文件
        String configFile = this.getClass().getResource("/tracker.conf").getFile();
        if (configFile != null) {
            // 初始化
            ClientGlobal.init(configFile);
            // 创建trackerClient
            TrackerClient trackerClient = new TrackerClient();
            // 创建trackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            // 创建StorageClient
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
            // 文件上传
            // 获取文件后缀名
            String extName = FilenameUtils.getExtension(file.getOriginalFilename());
            // 获取文件上传之后的URL group1/M00/00/03/wKjIgGJsSi6EDczNAAAAACY3A9Q146.png
            path = storageClient1.upload_appender_file1(file.getBytes(), extName, null);
            System.out.println(path);

        }
        // 返回最终路径
        return Result.ok(fileServerUrl + path);
    }
}
